function getName() {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user) {
	    console.log ("Currently logged in:  " + user["name"]);
	    document.getElementById("name-goes-here").innerText= user["name"];
	 } else {
	    console.log ("No one is logged in");
	 }
}
getName(); //run the function

function addCupListener() {
	document.getElementById("addCupButton").addEventListener("click", function () {
		console.log("Add Cup clicked!");
		
		// find out who is logged in
		var user = JSON.parse(localStorage.getItem("loggedinUser"));
		if (user) {
			console.log("Currently logged in:  " + user["name"]);
			console.log("Current count is ", + user["count"]);

			//increment the counter, save into loggedinUser
			user["count"]++;
			localStorage.setItem("loggedinUser", JSON.stringify(user));

			//get the users collection, and update the count for THAT user
			updateUsersCount(user["email"], user["count"]);

			// display it
			document.getElementById("coffee-count-goes-here").innerText = user["count"];
		} else {
			console.log("No one is logged in");
		}
	})
}
addCupListener();

// This function will go to the "users" collection in Local Storage
// find the one that matches this email
// Updates the count value with the new value
// Saves it back to Local Storage

function updateUsersCount(email, countValue){
	var users = JSON.parse(localStorage.getItem("users"));
	if (users) {
		const person = users.find(u => u.email === email);
		if (person) {
			person.count = countValue;
			addToHistory(person);
		}
		localStorage.setItem("users", JSON.stringify(users));
	}
}

function addToHistory(person){
	// read the current history array
	// push this add-event into the history array
	const now = new Date();
	const formatted = now.toLocaleString('en-US', { 
		weekday: 'long',  // "Monday", "Tuesday", etc.
		year: 'numeric',  // "2021", "2022", etc.
		month: 'long',    // "January", "February", etc.
		day: 'numeric',   // 1, 2, 3, etc.
		hour: 'numeric',  // 12 AM, 1 PM, etc.
		minute: 'numeric',
		second: 'numeric'
	});
  if (person.history === null)    //if there are no users yet
		person.history = [];          //initialize it to empty
	console.log (person.history);
  person.history.push({date:formatted});
}